// pages/main/chat/chat.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    members: [
      {
        id: 1,
        name: '小周',
        img: '/assets/chat/member1.png'
      },
      {
        id: 2,
        name: '小陈',
        img: '/assets/chat/member2.png'
      },
      {
        id: 3,
        name: '小林',
        img: '/assets/chat/member3.png'
      },
      {
        id: 4,
        name: '小何',
        img: '/assets/chat/member4.png'
      }
    ],
    messages: [
      {
        content: '有没有好姐妹能帮我带一下快递回来嘟',
        avatar: '/assets/chat/member3.png',
        type: 'sender',
        time: '09:30',
        audio: null,
        image: null,
        isPlaying: false
      },
      {
        content: '天啦噜，你怎么不能自己去取啊？说不定还有机会碰到你的Crush呀',
        avatar: '/assets/chat/member2.png',
        type: 'sender',
        time: '09:31',
        audio: null,
        image: null,
        isPlaying: false
      },
      {
        content: '你怎么这么多快递，惩罚你给我买Macbook Air',
        avatar: '/assets/chat/member4.png',
        type: 'sender',
        time: '09:32',
        audio: null,
        image: null,
        isPlaying: false
      },
      {
        content: '@小林 快递码发我一下',
        avatar: '/assets/chat/member1.png',
        type: 'receiver',
        time: '09:45',
        audio: null,
        image: null,
        isPlaying: false
      },
      {
        content: '好嘟好嘟，谢谢姐妹~',
        avatar: '/assets/chat/member3.png',
        type: 'sender',
        time: '10:15',
        audio: null,
        image: null,
        isPlaying: false
      }
    ], 
    inputValue: '' ,
    tempImages: [],
    recording: false, // 录音状态
    recorderManager: null, // 录音管理器
    audioContext: null, // 音频播放上下文
    currentPlayingIndex: -1
  },
  
  inputChange(e) {
    this.setData({
      inputValue: e.detail.value
    });
  },
  getCurrentTime() {
    const now = new Date();
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    return `${hours}:${minutes}`;
  },
  sortMessages(messages) {
    return [...messages].sort((a, b) => {
      const timeA = a.time.split(':').map(Number);
      const timeB = b.time.split(':').map(Number);
      return (timeA[0] * 60 + timeA[1]) - (timeB[0] * 60 + timeB[1]);
    });
  },
  sendMessage() {
    const { inputValue, messages } = this.data;
    if (inputValue.trim()!== '') {
      const newMessage = {
        type:'receiver',
        content: inputValue,
        avatar: '/assets/chat/member1.png',
        time: this.getCurrentTime()
      };
      const updatedMessages = this.sortMessages([...messages, newMessage]);
      this.setData({
        messages: updatedMessages,
        inputValue: ''
      });
    }
  },
  // 选择图片
  chooseImage() {
    wx.chooseImage({
      count: 1, // 一次只选一张图
      sizeType: ['compressed'], // 使用压缩图
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFilePaths;
        this.sendImage(tempFilePaths[0]); // 直接发送图片
      },
      fail: (err) => {
        console.error('选择图片失败:', err);
      }
    });
  },

  sendImage(tempFilePath) {
    const { messages } = this.data;
    const newMessage = {
      type:'receiver',
      image: tempFilePath, // 图片本地路径
      avatar: '/assets/chat/member1.png',
      time: this.getCurrentTime()
    };
    const updatedMessages = this.sortMessages([...messages, newMessage]);
    this.setData({
      messages: updatedMessages
    });
    // 如果需要上传到服务器，可在这里调用上传方法
    // this.uploadImage(tempFilePath);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const recorderManager = wx.getRecorderManager();
    this.setData({ recorderManager });
    recorderManager.onStop((res) => {
      if (res.tempFilePath) {
        this.sendAudio(res.tempFilePath, res.duration);
      }
    });
  },
  // 开始录音
  startRecord() {
    const { recorderManager } = this.data;
    const options = {
      format: 'mp3',
      duration: 60000, // 最长60秒
      sampleRate: 44100
    };
    
    recorderManager.options = options;
    recorderManager.start();
    this.setData({ recording: true });
  },

  // 停止录音
  stopRecord() {
    const { recorderManager } = this.data;
    recorderManager.stop();
    this.setData({ recording: false });
  },
  updateMessage(index, newData) {
    const messages = [...this.data.messages];
    messages[index] = { ...messages[index], ...newData };
    this.setData({ messages });
  },
  // 发送音频消息
  sendAudio(tempFilePath, duration) {
    const { messages } = this.data;
    const newMessage = {
      type:'receiver',
      audio: tempFilePath, // 音频临时路径
      duration: duration,
      avatar: '/assets/chat/member1.png',
      time: this.getCurrentTime()
    };
    const updatedMessages = this.sortMessages([...messages, newMessage]);
    this.setData({ messages: updatedMessages });
  },
  
  toggleAudio(e) {
    const index = e.currentTarget.dataset.index;
    const { messages, currentPlayingIndex, audioContext } = this.data;
    const message = messages[index];
    if (index === currentPlayingIndex) {
      if (audioContext) {
        audioContext.pause();
        this.updateMessage(index, { isPlaying: false });
        this.setData({ currentPlayingIndex: -1 });
      }
      return;
    }
    if (audioContext) {
      audioContext.stop();
      if (currentPlayingIndex !== -1) {
        this.updateMessage(currentPlayingIndex, { isPlaying: false });
      }
    }
    const context = wx.createInnerAudioContext();
    context.src = message.audio;
    context.onPlay(() => {
      this.updateMessage(index, { isPlaying: true });
    });
    context.onStop(() => {
      this.updateMessage(index, { isPlaying: false });
    });
    context.onEnded(() => {
      this.updateMessage(index, { isPlaying: false });
      this.setData({ currentPlayingIndex: -1 });
    });
    context.onError((err) => {
      console.error('音频播放错误:', err);
      this.updateMessage(index, { isPlaying: false });
    });
    
    context.play();
    this.setData({ 
      audioContext: context,
      currentPlayingIndex: index 
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (this.data.audioContext) {
      this.data.audioContext.destroy();
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})